package org.geektimes.web.mvc.header;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.geektimes.base.util.ReflectionUtils;
import org.geektimes.web.mvc.header.matedata.ParamInfo;
import org.geektimes.web.mvc.header.matedata.WebContent;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;

/**
* query类型参数解析  
* @author : lsq
*/
public   class QueryParamParse extends AbstractParamParse {



	@Override
	protected Object parse0(WebContent webContent, ParamInfo paramInfo) {
		try {
			HttpServletRequest httpServletRequest = toHttp(webContent.getRequest());
			//实体类
			if (!CollectionUtils.isEmpty(paramInfo.getFields())) {
				Object o = paramInfo.getType().newInstance();
				for (Field field : paramInfo.getFields()) {
					String paramName = "";
					if (!StringUtils.isEmpty(paramInfo.getName())){
						paramName = paramInfo.getName() + "." + field.getName();
					}
					ReflectionUtils.set(field , o , getValueByHttp(httpServletRequest , field.getType() , paramName));
				}
				return o;
			}
			//简单类型
			else {
				return getValueByHttp(httpServletRequest ,  paramInfo.getType() ,paramInfo.getName());
			}
		}catch (Exception e){
			throw new IllegalStateException(e);
		}
	}


	/**
	 * 获取http中的参数
	 * @param httpServletRequest 请求对象
	 * @param type 参数类型
	 * @param name 参数名称
	 * @return
	 */
	private Object getValueByHttp(HttpServletRequest httpServletRequest , Class type, String name){
		Object value;
		String parameter = httpServletRequest.getParameter(name);
		if (parameter == null){
			value = (String) httpServletRequest.getAttribute(name);
		}else {
			value =transType(parameter , type);
		}
		return value;
	}


}
